package controllers

import (
	"github.com/beego/beego/v2/core/logs"
	"personal-skill/models"
	"personal-skill/util/resultutil"
	"strings"
)

type ApplicationController struct {
	BaseController
}

func (appController *ApplicationController) Get() {
	id, err := appController.GetInt64("id")
	if err != nil {
		appController.ResponseJson(resultutil.Error(resultutil.RequestParamErr))
	}
	application := models.Application{Id: id}
	err = application.GetById()
	if err != nil {
		appController.ResponseJson(resultutil.Error(resultutil.ApplicationNotFoundErr))
	}
	appController.ResponseJson(resultutil.SuccessWithData(application))
}

func (appController *ApplicationController) Post() {
	application := models.NewApplication()
	err := appController.ParseForm(application)
	if err != nil {
		logs.Error(err)
		appController.ResponseJson(resultutil.Error(resultutil.RequestParamErr))
	}
	save, err := application.Save()
	if err != nil || save < 1 {
		logs.Error(err)
		appController.ResponseJson(resultutil.Error(resultutil.ApplicationAddFailErr))
	}
	appController.ResponseJson(resultutil.Success())
}

func (appController *ApplicationController) Put() {
	application := models.NewApplication()
	err := appController.ParseForm(application)
	if err != nil {
		logs.Error(err)
		appController.ResponseJson(resultutil.Error(resultutil.RequestParamErr))
	}
	var updateFields []string
	if len(strings.TrimSpace(application.Title)) > 0 {
		updateFields = append(updateFields, "title")
	}
	if len(strings.TrimSpace(application.Content)) > 0 {
		updateFields = append(updateFields, "content")
	}

	update, err := application.Update(updateFields...)
	if err != nil || update < 1 {
		logs.Error(err)
		appController.ResponseJson(resultutil.Error(resultutil.ApplicationUpdateFailErr))
	}
	appController.ResponseJson(resultutil.Success())
}

func (appController *ApplicationController) Delete() {
	id, err := appController.GetInt64("id")
	if err != nil {
		logs.Error(err)
		appController.ResponseJson(resultutil.Error(resultutil.RequestParamErr))
	}
	application := models.NewApplication()
	application.Id = id
	err = application.DelLogic()
	if err != nil {
		logs.Error(err)
		appController.ResponseJson(resultutil.Error(resultutil.ApplicationDelFailErr))
	}
	appController.ResponseJson(resultutil.Success())
}
